import { create } from 'zustand'
import { SEPARATOR_TEXT } from './constants'

import { produce } from 'immer'
import { ChatMessageType, CitationsType, LimitInfoType } from './types'

export type chatState = {
  running: boolean
  chatId: string // 应用id
  messages: ChatMessageType[] // 包含到目前为止的对话的消息列表。
  historyEnd: boolean // 没有更多历史纪录
  showGuideQuestion: boolean // 控制引导问题的显示状态
  /**
   * 1、根据短期记忆中最后轮次进行控制，
   * 2、时间控制范围内数量>=5,前端只取最后5轮，数量<=5时按时间控制
   */
  limitInfo: LimitInfoType
  upIsLoading: boolean
  includedAudioPlugin: boolean
  includedLenovoCloudPlugin: boolean
}

type Actions = {
  updateChatId: (chatId: string) => void
  loadHistoryMsg: (history: any, chatId: string) => Promise<void> // 会话获取历史记录
  loadMoreHistoryMsg: (chatId: string) => Promise<void>
  destroyChat: () => void
  createSendMsg: (
    type: 'text' | 'image_url' | 'file_url',
    text?: string,
    img?: string,
    imgName?: string,
    fileUrl?: string,
    fileName?: string
  ) => void
  startNewRound: (ignore?: boolean) => void
  updateLoadingMessage: () => void
  updateCurrentMessage: (
    chatId: string,
    text: string,
    status: number,
    internetCitations?: any,
    clear?: boolean,
    think?: string,
    thinkTime?: number,
    chatStopTag?: string
  ) => void
  updateCurrentMessageImage: (
    imgUrl: {
      type: string
      fileContextId?: string
      filename?: string
      url?: string
    },
    chatId: string,
    text: string,
    status: number,
    internetCitations?: any,
    clear?: boolean,
    think?: string,
    thinkTime?: number,
    chatStopTag?: string
  ) => void
  updateCitationsMessage: (chatId: string, citation: CitationsType | any, clear?: any) => void
  updateGuideMessage: (text: string, ignore?: boolean) => void
  setShowGuideQuestion: (status: boolean) => void
  updateLimitInfo: (limitInfo: LimitInfoType) => void
  setIsRunning: (running: boolean) => void
  setUpIsLoading: (loading: boolean) => void
}

export const getDefaultChatState = () => {
  return {
    running: false,
    chatId: '',
    messages: [],
    historyEnd: false,
    showGuideQuestion: false,
    limitInfo: {
      remember_mode: 0, // 0 最后轮次，1 最后分钟数
      remember_last_num: 5,
      remember_last_minute: 60
    },
    upIsLoading: false,
    includedAudioPlugin: false,
    includedLenovoCloudPlugin: false
  }
}

/**
 * 会话信息存储
 */
export const useChatStore = create<chatState & Actions>((set, get) => ({
  ...getDefaultChatState(),
  updateChatId(chatId) {
    console.log('>>>changeChatId: ', chatId)
    set({ ...getDefaultChatState(), chatId })
  },

  destroyChat() {
    set({ ...getDefaultChatState() })
  },
  // todo history相关与后端确认,需提供与当前chat数据格式接口一致的接口
  async loadHistoryMsg(history: any, chatId: string) {
    try {
      const currentChatId = get().chatId
      set(state => ({
        messages: chatId !== currentChatId ? [...history.messages] : [...state.messages, ...history.messages]
      }))
    } catch (error) {
      console.error('Failed to load history messages:', error)
    }
  },

  async loadMoreHistoryMsg(history: any) {
    try {
      // const currentPage = Math.ceil(get().messages.length / 5) + 1
      // const history = await getHistoryMessagesApi(chatId, currentPage, 5)
      set(state => ({
        messages: [...state.messages, ...history.messages]
        // historyEnd: history.total <= state.messages.length + history.messages.length
      }))
    } catch (error) {
      console.error('Failed to load more history messages:', error)
    }
  },

  createSendMsg(
    type: 'text' | 'image_url' | 'file_url',
    text: string,
    img: string,
    imgName: string,
    fileUrl: string = '',
    fileName: string = ''
  ) {
    const messages = get().messages.filter(msg => msg.role !== 'loading')
    // 同一批输入的图片和文本合并为一条消息中多个content
    const lastMessage = messages[messages.length - 1]
    const isLastUserAssistant = lastMessage?.role === 'user'

    const newContent = {
      type,
      ...(img && {
        image_url: {
          url: img,
          detail: 'auto',
          name: imgName
        }
      }),
      ...(fileUrl && {
        file_url: {
          url: fileUrl,
          name: fileName
        }
      }),
      text
    }
    let newMessage: ChatMessageType = {
      role: 'user',
      content: [newContent],
      createTime: Date.now()
    }
    if (isLastUserAssistant) {
      newMessage = produce(lastMessage, (draft: ChatMessageType) => {
        draft.content = [...draft.content, newContent]
      })
    }
    set(state => ({
      messages: isLastUserAssistant ? [...messages.slice(0, -1), newMessage] : [...messages, newMessage]
    }))
  },
  updateLoadingMessage() {
    const loadingMessage = {
      role: 'loading',
      content: [
        {
          type: 'text',
          text: ''
        }
      ],
      ignore: true
    }
    set(state => ({ messages: [...state.messages, loadingMessage] }))
  },
  updateCurrentMessage(
    chatId: string,
    content: string,
    status,
    internetCitations = [],
    clear = false,
    think = '',
    thinkTime = 0,
    chatStopTag: string
  ) {
    console.log(
      'updateCurrentMessage',
      chatId,
      content,
      status,
      internetCitations,
      clear,
      think,
      thinkTime,
      chatStopTag
    )
    const currentChatId = get().chatId
    if (chatId !== currentChatId) {
      return
    }
    const messages = get().messages.filter(msg => msg.role !== 'loading')
    // 同一批响应的文本合并为一条消息
    const lastMessage = messages[messages.length - 1]
    const isLastMessageAssistant = lastMessage?.role === 'assistant'

    const newTextContent = isLastMessageAssistant && !clear ? lastMessage.content[0].text + content : content
    const newCitations = !clear ? internetCitations : []
    const newThink = isLastMessageAssistant && !clear ? lastMessage.content[0].think + think : think
    const newThinkTime =
      isLastMessageAssistant && lastMessage.content[0].thinkTime ? lastMessage.content[0].thinkTime : thinkTime

    const newMessage = {
      role: 'assistant',
      content: [
        {
          type: 'text',
          text: newTextContent,
          internetCitations: newCitations,
          think: newThink,
          thinkTime: newThinkTime,
          // 判断生成停止 显示文案 = 已停止生成
          chatStopTag
        }
      ],
      createTime: Date.now(),
      status
    }

    const newMessages = isLastMessageAssistant ? [...messages.slice(0, -1), newMessage] : [...messages, newMessage]
    set(state => ({ messages: newMessages }))
  },
  // 将图片信息追加到正在接收的message对应content中
  updateCurrentMessageImage(
    imgUrl: {
      type: string
      fileContextId?: string
      filename?: string
      url?: string
    },
    chatId: string,
    content: string,
    status,
    internetCitations = [],
    clear = false,
    think = '',
    thinkTime = 0,
    chatStopTag: string
  ) {
    const currentChatId = get().chatId
    if (chatId !== currentChatId) {
      return
    }
    const messages = get().messages.filter(msg => msg.role !== 'loading')
    // 同一批响应的文本合并为一条消息
    const lastMessage = messages[messages.length - 1]
    const isLastMessageAssistant = lastMessage?.role === 'assistant'

    const newTextContent = isLastMessageAssistant && !clear ? lastMessage.content[0].text + content : content
    const newCitations = !clear ? internetCitations : []
    const newThink = isLastMessageAssistant && !clear ? lastMessage.content[0].think + think : think
    const newThinkTime =
      isLastMessageAssistant && lastMessage.content[0].thinkTime ? lastMessage.content[0].thinkTime : thinkTime
    const newImgUrl =
      isLastMessageAssistant && lastMessage.content[0].image_url ? lastMessage.content[0].image_url : imgUrl

    const newMessage = {
      role: 'assistant',
      content: [
        {
          type: 'image_url',
          text: newTextContent,
          internetCitations: newCitations,
          think: newThink,
          thinkTime: newThinkTime,
          image_url: newImgUrl,
          chatStopTag
        }
      ],
      createTime: Date.now(),
      status
    }

    const newMessages = isLastMessageAssistant ? [...messages.slice(0, -1), newMessage] : [...messages, newMessage]
    set(state => ({ messages: newMessages }))
  },
  updateCitationsMessage(chatId: string, citation: CitationsType, clear?: string) {
    /* clear = 暂停会话清除命中效果 */
    const currentChatId = get().chatId
    if (chatId !== currentChatId) {
      return
    }
    const messages = get().messages.filter(msg => msg.role !== 'loading')
    const lastMessage = messages[messages.length - 1]
    const isLastMessageAssistant = lastMessage?.role === 'citations'

    const citationsMsg = {
      role: 'citations',
      // citations: [citation],
      citations: clear ? [] : isLastMessageAssistant ? [...lastMessage.citations, citation] : [citation],
      ignore: true
    }
    // const messages = get().messages
    // const newMessage = messages.filter(msg => msg.role !== 'loading')
    // set(state => ({ messages: [...messages, citationsMsg] }))
    const newMessages = isLastMessageAssistant ? [...messages.slice(0, -1), citationsMsg] : [...messages, citationsMsg]
    set(state => ({ messages: newMessages }))
    get().updateLoadingMessage()
  },
  startNewRound(ignore = false) {
    set(state => ({
      showGuideQuestion: true,
      messages: [
        ...state.messages,
        {
          role: 'system',
          content: [
            {
              type: 'text',
              text: SEPARATOR_TEXT
            }
          ],
          ignore
        }
      ]
    }))
  },
  updateGuideMessage(text, ignore = false) {
    set(state => ({
      messages: [
        ...state.messages,
        {
          role: 'system',
          content: [
            {
              type: 'text',
              text
            }
          ],
          ignore
        }
      ]
    }))
  },
  setShowGuideQuestion(status: boolean) {
    set({ showGuideQuestion: status })
  },
  updateLimitInfo(limitInfo) {
    set(state => ({
      limitInfo: { ...limitInfo }
    }))
  },
  setIsRunning(running: boolean) {
    set({ running })
  },
  setUpIsLoading(loading: boolean) {
    set({ upIsLoading: loading })
  }
}))
